package com.fun.feifun.modules.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fun.feifun.base.utils.RedisUtil;
import com.fun.feifun.modules.business.model.BusinessBlacklist;
import com.fun.feifun.modules.business.dao.BusinessBlacklistMapper;
import com.fun.feifun.modules.business.service.IBusinessBlacklistService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fun.feifun.modules.sys.parameter.constant.ParameterConstant;
import com.fun.feifun.modules.sys.parameter.service.ISysParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 业务黑名单手机号 服务实现类
 * </p>
 *
 * @author wkf
 * @since 2024-09-22
 */
@Service
public class BusinessBlacklistServiceImpl extends ServiceImpl<BusinessBlacklistMapper, BusinessBlacklist> implements IBusinessBlacklistService {

    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private ISysParameterService parameterService;

    public void add(String phone) {
        Object value = redisUtil.get("fail-list:" + phone);
        Integer  failCount= value==null?0:(Integer)value;

        //获取阈值
        Integer thresholdCount=ParameterConstant.BLACKLIST_THRESHOLD_DEFAULT_VALUE;
        String threshold = parameterService.getParameByCode(ParameterConstant.BLACKLIST_THRESHOLD);
        if(StringUtils.isNotEmpty(threshold)){
            thresholdCount=Integer.parseInt(threshold);
        }

        if(failCount++<thresholdCount){
            redisUtil.set("fail-list:" + phone, failCount);
            return;
        }
        redisUtil.delete("fail-list:" + phone);
        redisUtil.setEx("blacklist:"+phone, "1", 60*60*24);
        BusinessBlacklist black=new BusinessBlacklist();
        black.setPhone(phone);
        black.setFailCount(failCount);
        black.setUpdateTime(LocalDateTime.now());
        QueryWrapper<BusinessBlacklist> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(BusinessBlacklist::getPhone,phone);
        saveOrUpdate(black,queryWrapper);
    }

    public Boolean delete(String phone) {
        redisUtil.delete("blacklist:" + phone);
        redisUtil.delete("fail-list:" + phone);
        QueryWrapper<BusinessBlacklist> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(BusinessBlacklist::getPhone,phone);
        return remove(queryWrapper);
    }

    public Boolean clear() {
        redisUtil.delete("blacklist:" );
        redisUtil.delete("fail-list:" );
        QueryWrapper<BusinessBlacklist> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().ne(BusinessBlacklist::getId,0);
        return remove(queryWrapper);
    }
}
